//
//  ViewController.m
//  TestNearByS
//
//  Created by apple on 15/9/6.
//  Copyright (c) 2015年 CXM. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

static NSString * const XXServiceType = @"xx-service";

- (void)viewDidLoad {
    [super viewDidLoad];
    _peerID = [[MCPeerID alloc] initWithDisplayName:[[UIDevice currentDevice] name]];
    
    _session = [[MCSession alloc] initWithPeer:_peerID
                              securityIdentity:nil
                          encryptionPreference:MCEncryptionNone];
    _session.delegate = self;

     self.status.text=@"NotConnected";
    
    _advertiser =
    [[MCNearbyServiceAdvertiser alloc] initWithPeer:_peerID
                                      discoveryInfo:nil
                                        serviceType:XXServiceType];
    _advertiser.delegate = self;
    
    [_advertiser startAdvertisingPeer];
    
    
    
    
    _browser = [[MCNearbyServiceBrowser alloc] initWithPeer:_peerID serviceType:XXServiceType];
    _browser.delegate = self;
    [_browser startBrowsingForPeers];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state
{
    switch (state) {
        case MCSessionStateConnected:
            self.status.text=@"Connected";
            break;
        case MCSessionStateConnecting:
            
             self.status.text=@"Connecting";
            break;
        case MCSessionStateNotConnected:
              self.status.text=@"NotConnected";
            break;
        default:
            break;
    }

}

- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID
{
    
    NSString * message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.chatTextView.text=[[NSString alloc] initWithFormat:@" %@  Say : %@",peerID.displayName,message];
    });
    NSLog(@"------");

}

- (void)session:(MCSession *)session didReceiveStream:(NSInputStream *)stream withName:(NSString *)streamName fromPeer:(MCPeerID *)peerID
{


}

- (void)session:(MCSession *)session didStartReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID withProgress:(NSProgress *)progress
{


}

- (void)session:(MCSession *)session didFinishReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID atURL:(NSURL *)localURL withError:(NSError *)error
{



}


- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void (^)(BOOL, MCSession *))invitationHandler
{


    
    invitationHandler(true,_session);

}



- (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info
{
    NSLog(@"----------%@",peerID.displayName);
    
    [browser invitePeer:peerID toSession:_session withContext:nil timeout:0];
    
}


- (void)browser:(MCNearbyServiceBrowser *)browser lostPeer:(MCPeerID *)peerID
{
    
    
    NSLog(@" lostPeer %@", peerID);
    
}

- (IBAction)clickButton:(id)sender {
    
    
    [self sendMessage:self.sendText.text];
    
    self.sendText.text=@"";
}

-(void)sendMessage:(NSString *)message
{


    NSData *messageData = [message dataUsingEncoding:NSUTF8StringEncoding];
    // Send text message to all connected peers
    NSError *error;
    [self.session sendData:messageData toPeers:self.session.connectedPeers withMode:MCSessionSendDataReliable error:&error];
    // Check the error return to know if there was an issue sending data to peers.  Note any peers in the 'toPeers' array argument are not connected this will fail.
    if (error) {
        NSLog(@"Error sending message to peers [%@]", error);
        
    }
}

@end
